package edu.umn.msse.farside.FourH.web;

import com.dreamlizard.miles.beans.TimestampPropertyEditor;
import edu.umn.msse.farside.FourH.domain.Event;
import edu.umn.msse.farside.FourH.domain.Volunteer;
import edu.umn.msse.farside.FourH.services.EventService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpSession;
import java.sql.Timestamp;
import java.util.Date;

/**
 * Created by IntelliJ IDEA.
 * User: corcutt
 * Date: Mar 15, 2009
 * Time: 3:21:04 PM
 * To change this template use File | Settings | File Templates.
 */
@Controller
@RequestMapping("/createEvent")
public class CreateEventController
{
    private EventService eventService;
    private final EventValidator eventValidator = new EventValidator();

    @Autowired
    public void setEventService(EventService eventService)
    {
        this.eventService = eventService;
    }

    @RequestMapping(method = RequestMethod.GET)
    public String createEvent2(Model model)
    {
        Event event = new Event();
        Date today = new Date();
        event.setStartDateAndTime(new Timestamp(today.getTime()));
        event.setEndDateAndTime(new Timestamp(today.getTime()));
        model.addAttribute("event", event);

        return "createEvent";
    }

    @InitBinder
    public void initBinder(WebDataBinder binder)
    {
        binder.registerCustomEditor(Timestamp.class, new TimestampPropertyEditor());
    }

    @RequestMapping(method = RequestMethod.POST)
    public String createEvent(@ModelAttribute(value = "event") Event event, BindingResult result, HttpSession session)
    {
        eventValidator.validate(event, result);

        // set the administrator to the current user
        event.setAdministrator((Volunteer) session.getAttribute("volunteer"));
        if (!result.hasErrors())
        {
            eventService.addEvent(event);
        }

        return result.hasErrors() ? "createEvent" : "redirect:/fourH/myEvents";
    }

}
